package wait_notify.produce_consume;

import lombok.extern.slf4j.Slf4j;
import util.Sleeper;

import java.util.Deque;
import java.util.LinkedList;

@Slf4j(topic = "c.ProduceConsumer")
public class ProduceConsumer {
    public static void main(String[] args) {
        MessageQueue queue = new MessageQueue(2);
        for (int i = 0; i < 3; i++) {
            int id = i;
            new Thread(() -> {
                queue.put(new Message(id, "content--" + id));
            }, "生产者" + i).start();
            new Thread(() -> {
                while (true){
                    Sleeper.sleep(1);
                    Message message = queue.take();
                }
            }, "消费者" + i).start();
        }
    }
}

//消息队列类，实现Java线程间的异步通信
@Slf4j(topic = "c.MessageQueue")
class MessageQueue {
    //消息的队列集合
    private Deque<Message> list = new LinkedList<>();
    //消息队列的容量
    private int capacity;

    MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    //获取消息
    public Message take() {
        synchronized (list) {
            while (list.isEmpty()) {
                try {
                    log.debug("队列为空");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //从队头获取消息并返回
            Message message = list.removeFirst();
            log.debug("已消费消息：{}", message);
            list.notifyAll();
            return message;
        }
    }

    //存入消息
    public void put(Message message) {
        synchronized (list) {
            // 检查对队列是否已满
            while (list.size() == capacity) {
                try {
                    log.debug("队列已满");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 将消息加入队列尾部
            list.addLast(message);
            log.debug("已生产消息：{}", message);
            list.notifyAll();
        }
    }
}

final class Message {
    private final int id;
    private final Object value;

    Message(int id, Object value) {
        this.id = id;
        this.value = value;
    }

    public Object getValue() {
        return value;
    }

    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", value=" + value +
                '}';
    }
}

